package com.yunchuang.controller.user;

import cn.hutool.core.codec.Base64Encoder;
import com.google.gson.Gson;
import com.yunchuang.model.pojo.User;
import com.yunchuang.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 获取用户头像
 *
 * @author ItJiange
 * @date 2023/10/22
 */
@WebServlet("/getUserAvatar")
public class UserAvatarController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        // 获取头像路径
        String avatar = user.getAvatar();
        // 将头像路径转为 BASE64 存储
        String encoderAvatar = getAvatarEncoder(avatar);
        user.setAvatar(encoderAvatar);
        // 将 Object 对象转为 JSON 对象 并返回前端
        JSONUtils.writeOutJSON(user, resp);
        Gson gson = new Gson();
        String userJson = gson.toJson(user);
        System.out.println(userJson);
        // 获取打印流
        PrintWriter writer = resp.getWriter();
        writer.write(userJson);
        writer.flush();
        writer.close();
    }

    /**
     * 将路径转为 BASE64 存储
     * @param avatar 头像路径
     * @return
     */
    private static String getAvatarEncoder(String avatar) {
        String encoder = "data:image/jpg;base64,"; //定义图片类型，方便前端直接使用
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try (FileInputStream is = new FileInputStream(avatar)) {
            is.transferTo(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        encoder = encoder + Base64Encoder.encode(data.toByteArray()).replace("\r\n", "").trim();
        return encoder;
    }
}
